package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.service.IStrategyStratisVoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVo;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {
    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IStrategyStratisVoRedisService strategyStratisVoRedisService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void save(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return strategyRepository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> listAll() {
        return strategyRepository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();
        //条件：目的地查
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        // 条件：主题查
        if (StringUtils.hasLength(qo.getThemeId())) {
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        // 条件：首页显示上架
        if (qo.getState() != null) {
            query.addCriteria(Criteria.where("state").is(Strategy.STATE_PUBLISH));   // 上架
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"viewnum");
        return DBHelper.query(mongoTemplate,query,Strategy.class,pageable);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        // 冗余字段的维护
        // 1、关联的目的地（id、name；通过攻略分类找到即可）
        StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
        strategy.setDestId(catalog.getDestId());
        strategy.setDestName(catalog.getDestName());
        // 2、主题名字
        strategy.setThemeName(strategyThemeService.get(strategy.getThemeId()).getName());
        // 3、分类名字
        strategy.setCatalogName(catalog.getName());

        // 国内外（用吐司的方法，获取吐司list中的第1个，判断是否是中国）  需要进行判断获取的吐司是否为空，中国的老爸是为空的
        List<Destination> destinations = destinationService.getToasts(catalog.getDestId());
        if (destinations !=null && destinations.size() > 0){
            String name = destinations.get(0).getName();
            strategy.setIsabroad("中国".equals(name)?Strategy.ABROAD_NO:Strategy.ABROAD_YES);
        }

        if (StringUtils.hasLength(strategy.getId())){
            // 5、数据统计（5个量，新增默认为0，修改要查到后保存，保证数据的一致性）、时间
            Strategy str = this.get(strategy.getId());
            strategy.setFavornum(str.getFavornum());
            strategy.setViewnum(str.getViewnum());
            strategy.setReplynum(str.getReplynum());
            strategy.setSharenum(str.getSharenum());
            strategy.setThumbsupnum(str.getThumbsupnum());

            strategy.setCreateTime(str.getCreateTime());
            this.update(strategy);
        }else {
            // 4、创建时间（新增需要保存，修改要查到后重新保存）
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    @Override
    public void changeState(int state, String id) {
        // 查 改 保存
        Strategy strategy = strategyRepository.findById(id).orElse(null);
        strategy.setState(state);
        this.save(strategy);
    }

    @Override
    public List<Strategy> findByCatalogId(String id) {
        return strategyRepository.findByCatalogId(id);
    }

    @Override
    public List<Strategy> findByDestId(String destId) {
        // 点击量前3（排序：阅读量，分页：前3）
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        return strategyRepository.findByDestIdAndState(destId,pageable,Strategy.STATE_PUBLISH);
    }

    @Override
    public StrategyStatisVo getstatisVo(String sid) {
        // 阅读数 + 1
        strategyStratisVoRedisService.viewnumIncrease(sid,1);
        return strategyStratisVoRedisService.getStrategyStatisVo(sid);
    }

    @Override
    public List<String> getUserStrategyFavor(String userId) {
        // 拼接key
        String key = RedisKeys.USER_STRATEGY_FAVOR.join(userId);
        // 判断key是否存在
        if (redisTemplate.hasKey(key)){
            String idsList = redisTemplate.opsForValue().get(key);
            return JSON.parseArray(idsList,String.class);
        }
        return new ArrayList<>();  // 不能是null，null没有初始化分配空间；空的数组有空间只是没有东西而已
    }

    @Override
    public List<Strategy> findByDestName(String destName) {
        return strategyRepository.findByDestName(destName);
    }
}
